/**
 * Created by bolin on 2016/12/13.
 */
var ActivityType={
    /// <summary>
    /// 开始节点
    /// </summary>
    'start': 0,
        /// <summary>
        /// 结束
        /// </summary>
        'end': 1,
        /// <summary>
        /// 起草节点
        /// </summary>
        'drafting': 2,

        /// <summary>
        /// 条件分支
        /// </summary>
        'condition': 3,

        /// <summary>
        /// 审批节点（包含并行和串行两种模式）
        /// </summary>
        'approval': 4,
        /// <summary>
        /// 审阅节点
        /// </summary>
        'freedom': 4,

        /// <summary>
        /// 分支
        /// </summary>
        'work': 5,
        /// <summary>
        /// 合并
        /// </summary>
        'freedom': 6,
        /// <summary>
        /// 子流程
        /// </summary>
        'subprocesses': 7

}
//鼠标事件
var MouseOperation = function () {
    var isActivityMove = false;
    var isRuleMove = false;
};
MouseOperation.prototype = {
    //leftbuttondown  单击

    leftbuttondown: function (e) {
        $.each(wf.activityHelper.Activitys, function (i, activity) {
            activity.isSelect = 0;
        });
        $.each(wf.rules, function (a, val) {
            val.isSelect = false;
        })
        //添加节点，
        if (wf.gcommand == command.addactivity) {
            wf.activityHelper.AddActivity(wf.canvasHelper.GetPoint(e), wf.currentActivityType);
        }
        else if (wf.gcommand == command.addrules) {
        }
        //选择操作
        else {
            //1、获得可能选中的节点
            var result = wf.canvasHelper.GetSelectedActivity(e);
            /*result.isSelect：true 有节点被选中
             false没有节点被选中
             */
            if (result.isSelect) {
                result.selectedObject.isSelect = 3;
                if (wf.selectedObjects.length > 0 && wf.selectedObjects.contains(result.selectedObject)) {
                    $.each(wf.selectedObjects, function (i, val) {
                        val.currentActivityPosition = val.position;
                        val.startMovePoint = wf.canvasHelper.GetPoint(e);
                    });
                    wf.moveActivity = true;
                } else {
                    //清除样式
                    wf.canvasHelper.ClearAllStyle();
                    result.selectedObject.SelectActivity(e, result.distinct);
                }
            } else {

                wf.selectedObjects = new Array();
                result = wf.canvasHelper.GetSelectedRule(e);
                //1、是否有规则被选中
                if (result.isSelect) {
                    wf.workspace.css("cursor", "pointer");
                    result.selectedObject.isSelect = true;
                    wf.currentRule = result.selectedObject;
                    wf.currentRule.SelectRule(result);
                    wf.canvasHelper.ClearAllStyle();
                } else {
                    //没有任何单元被选中
                    wf.canvasHelper.ClearAllStyle();
                    wf.gcommand = command.nulloperation;
                }
            }
        }
    },
    //鼠标左键弹起事件
    leftbuttonUp: function (e) {
        var me = this;
        if (!e.ctrlKey) {
            wf.selectedObjects = new Array();
        }
        var result = wf.canvasHelper.GetSelectedActivity(e);
        switch (wf.gcommand) {
            case command.addrules:
                if (result.isSelect) {
                    if (result.selectedObject != wf.currentRule.startActivity && result.selectedObject.CanHaveToRule()) {
                        wf.canvasHelper.AddRule(wf.currentRule, result.selectedObject);
                    }
                }
                else
                    wf.currentRule.AddPoint(wf.canvasHelper.GetPoint(e));
                break;
            case   "approval":
                wf.gcommand = command.nulloperation;
                break;
            case command.selectactivity:
                wf.moveActivity = false;
                if (wf.currentActivity.capture.iscapture)
                    wf.currentActivity.MoveActivity(wf.currentActivity.capture.point, 'tra');
                if (me.isActivityMove) {
                    me.isActivityMove = false;
                }
                wf.currentActivity.ResetActivity();
                break;
        }
        if (wf.moveRule) {
            wf.currentRule.ChangeActivity(wf.canvasHelper.GetPoint(e), result);
            if (me.isRuleMove) {
                isRuleMove = false;
            }
            wf.moveRule = false;
        }
        wf.workspace.css("cursor", "default");

    },
    //鼠标移动
    mouseMove: function (e) {
        if (document.getBoxObjectFor) {
            alert("");
        }
        var me = this;
        var point = wf.canvasHelper.GetPoint(e);
        if (wf.gcommand == command.addrules) {
            if (!wf.currentRule.startActivity.Picture.isPointInPath(e.offsetX, e.offsetY)) {
                var currentPoint = wf.canvasHelper.GetPoint(e);
                if (wf.currentRule.capture.iscapture)
                    currentPoint = wf.currentRule.capture.point
                wf.currentRule.DrawRule(currentPoint);
                wf.currentRule.DrawReferenceLine(point);
            }
        } else if (wf.gcommand == command.addactivity) {

        } else if (wf.moveActivity) {
            if (wf.selectedObjects.length == 0) {
                wf.currentActivity.MoveActivity(point);

                wf.currentActivity.DrawReferenceLine(point);
                me.isActivityMove = true;
            }
            else {
                $.each(wf.selectedObjects, function (i, val) {
                    val.MoveActivity(point);
                });
            }
        }
        else if (wf.moveRule) {
            wf.currentRule.ResetPoint(e);
            me.isRuleMove = true;
        }
        else {
            var result = wf.canvasHelper.GetSelectedActivity(e);
            $.each(wf.activityHelper.Activitys, function (i, activity) {
                if (activity.isSelect < 3)
                    activity.isSelect = 0;
                activity.isDrawRuleStart = false;
            });

            if (result.isSelect) {

                if (result.distinct > 10) {
                    wf.workspace.css("cursor", "pointer");
                    if (result.selectedObject.isSelect != 3)
                        result.selectedObject.isSelect = 1;
                }
                else if (result.selectedObject.CanHaveFromRule()) {
                    wf.workspace.css("cursor", "crosshair");
                    result.selectedObject.isDrawRuleStart = true;
                    if (result.selectedObject.isSelect != 3)
                        result.selectedObject.isSelect = 2;
                }

            }
            else {
                $.each(wf.activityHelper.Activitys, function (i, activity) {
                    if (activity.isSelect < 3)
                        activity.isSelect = 0;
                });
                result = wf.canvasHelper.GetSelectedRule(e);
                if (result.isSelect)
                    wf.workspace.css("cursor", "pointer");
                else
                    wf.workspace.css("cursor", "default");
            }
            wf.canvasHelper.ClearAllStyle();
        }
    },
    //鼠标右键
    rightbuttondown: function (e) {
        if (wf.gcommand == command.addrules) {
            wf.currentRule.Dispose();
            wf.gcommand = command.nulloperation;
        } else if (wf.gcommand == command.addactivity) {
            wf.gcommand = command.nulloperation;

        }

        return false;
    },

    ctrlKeybuttondown: function (e) {

        if (wf.selectedObjects.length == 0 && wf.gcommand == command.selectactivity) {
            wf.selectedObjects[0] = wf.currentActivity;
        }
        var result = wf.canvasHelper.GetSelectedActivity(e);
        if (result.isSelect) {
            wf.selectedObjects[wf.selectedObjects.length] = result.selectedObject;
            result.selectedObject.SelectActivity(e, result.distinct);
            $.each(wf.selectedObjects, function (i, val) {
                val.currentActivityPosition = val.position;
                val.startMovePoint = wf.canvasHelper.GetPoint(e);
            });
        }
    },
    //左键双击
    leftbuttondoubleclick: function (e) {
        var result = wf.canvasHelper.GetSelectedActivity(e);
        if (result.isSelect) {
            if (wf.gcommand == command.addrules)
                this.rightbuttondown();
            //显示节点属性
            result.selectedObject.ShowProperty();

        }
        else {
            result = wf.canvasHelper.GetSelectedRule(e);
            if (result.isSelect) {
                //显示规则线属性
                result.selectedObject.ShowProperty();
            }
        }
        return false;
    }
}

var toolbar = {
    islock: false,
    isdblclick: false,
    command: [],
    config: {
        file: {
            description: '文件 ',
            items: {
                save: {id: 'save', img: 'save.png', tag: '保存'}
            }
        },
        edit: {
            description: '编辑',
            items: {
                lock: {id: 'lock', img: 'lock.png', tag: '加锁'}
            }
        },
        activity: {
            description: '节点',
            items: {
                approval: {id: 'approval', img: 'approval.png', tag: '决策'},
                condition: {id: 'condition', img: 'condition.png', tag: '条件'},
                freedom: {id: 'freedom', img: 'freedom.png', tag: '自由'}
            }
        }
    },
    init: function (element) {
        $.each(toolbar.config, function (j, menu) {
            // var split = $("<li>").attr("class", "group").html(menu.description);
            // element.append(split);

            $.each(menu.items, function (i, val) {
                var image = $('<img>').attr('src', '/assets/js/workflow/images/toolbar/' + val.img);
                var li = $("<li>").dblclick(function () {
                    toolbar.isdblclick = true;
                    toolbar.mousedownCallBack(i);
                }).click(function () {
                    isDoubleClickCommand = false;
                    toolbar.mousedownCallBack(i, image);
                }).append(image).append(val.tag);
                if (command[i] == command.lock) {
                }
                element.append(li)
            });
        });
    },
    mousedownCallBack: function (cmd, image) {
        var me = this;
        var tmp = command.create;
        if (cmd in command)
            tmp = command[cmd];
        if (tmp == command.create || tmp == command.open || tmp == command.export || tmp == command.import) {
            switch (command[cmd]) {
                case command.create:
                    me.Create();
                    break;
                case command.open:
                    me.Open();
                    break;
                case command.import:
                    me.Import();
                    break;
            }
        }
        if (me.CanOperation) {
            if (cmd in ActivityType) {
                wf.gcommand = command.addactivity;
                wf.currentActivityType = ActivityType[cmd];
                wf.workspace.css("cursor", "crosshair");
            }
            else {
                switch (command[cmd]) {
                    case command.addrules:
                        wf.gcommand = cmd;
                        break;
                    case command.save:
                        SqlHelper.GetAllPackage(me.Save);
                        break;
                    case command.lock:
                        me.Edit(image);
                        break
                    case command.undo:
                        me.UndoCommand();
                        break;
                    case command.redo:
                        me.RedoCommand();
                        break;
                    case command.export:
                        me.Export();
                        break;
                }
            }
        }
    },
    Create: function (templateId) {
        var me = this;
        var layerNum = $.layer({
            type: 1,
            title: false,
            move: [$("#divorgTitle"), true],
            fix: false,
            closeBtn: true,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['360px', '420px'],
            page: {dom: $("#divOrg")},
            success: function () {
            }
        });
        $(".xubox_main").css("background-color", "transparent");
        OrgHelper.BindOrg(SqlHelper.OrgList);
        $("#btnCreateOK").unbind();
        $("#btnCreateCancel").unbind();
        $("#btnCreateOK").click(function () {

            var nodes = zTreeObj.getSelectedNodes();
            if (nodes.length > 0) {
                wf.orgId = nodes[0].id;
                SqlHelper.GetAllJob();
                canvasHelper.CreateTemplate();
                layer.close(layerNum);
                me.CanOperation = true;
                me.UnBind();

                //wf.canvas.unbind();
                //wf.canvas.dblclick(function (e) {
                //    e.stopPropagation();
                //    wf.mouseOperation.leftbuttondoubleclick(e);

                //});

                me.BindEvent();
                templateStatus = TemplateStatus.New;
                template = {id: templateId ? templateId : undefined};
                $("#divTemplateName").css('display', 'none');
            }
        });
        $("#btnCreateCancel").click(function () {
            layer.close(layerNum);
        });

    },
    Save: function (data) {
        debugger;
        var me = toolbar;
        $("#selectPackage").html("");
        $("#btnNewVersion").unbind();
        $("#btnEdit").unbind();
        $("#btnSaveOK").unbind();
        $("#btnSaveCancel").unbind();


        var package_id = template == undefined || template.id == undefined || template.id == null ? "" : template.id;


        $.each(data, function (i, val) {
            var option = package_id == val.id ? $("<option selected='selected'  value='" + val.id + "' >" + val.packageName + "</option>") : $("<option  value='" + val.id + "' >" + val.packageName + "</option>");
            $("#packageName").append(option);
        });

        var tmpName = template == undefined || template.templateName == undefined || template.templateName == null ? "" : template.templateName;
        $("#templateName").val(tmpName);
        var description = template == undefined || template.description == undefined || template.description == null ? "" : template.description;
        $("#description").val(description);

        $("#txtImg").val(template.imgurl || "");
        $("#templateName").val(tmpName);

        $('#save').modal();

        switch (wf.templateStatus) {
            case TemplateStatus.New:
                $("#btnNewVersion").css("display", "none");
                $("#btnEdit").css("display", "none");
                $("#btnSaveOK").click(function () {
                    template.guid = Guid.NewGuid();
                    template.publisType = 0;
                    me.SaveInvoke();
                });
                break;
            case TemplateStatus.Open:
                $("#btnNewVersion").css("display", "inline");
                $("#btnEdit").css("display", "inline");
                $("#btnNewVersion").click(function () {
                    template.publisType = 2;
                    me.ChangeID();
                    me.SaveInvoke();

                });
                $("#btnEdit").click(function () {
                    if (confirm('修改当前版本可能导致监控图显示不正确,是否继续？')) {
                        template.publisType = 1;
                        me.SaveInvoke();
                    }
                });
                $("#btnSaveOK").click(function () {
                    template.guid = Guid.NewGuid();
                    template.publisType = 0;
                    me.ChangeID();
                    me.SaveInvoke();
                });

                break;
            case TemplateStatus.Import:
                $("#btnNewVersion").css("display", "none");
                $("#btnEdit").css("display", "none");
                $("#btnNewVersion").click(function () {
                    me.ChangeID();
                    me.SaveInvoke('Workflow_AddTemplate');
                });
                $("#btnEdit").click(function () {
                    me.ChangeID();
                    template.versionNum += 1;
                    me.SaveInvoke('Workflow_UpdateTemplate');
                });
                $("#btnSaveOK").click(function () {

                    template.versionNum = 0;
                    me.ChangeID();
                    me.SaveInvoke('Workflow_AddTemplate');
                });
                break;
        }
    },
    //调用保存
    SaveInvoke: function () {
        debugger;
        var me = toolbar;
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        wf.activityHelper.GetReturnActivitys(wf.activityHelper.DraftingActivity);
        var result = {
            result: true,
            errorMessage: ''
        }
        $.each(wf.activityHelper.Activitys, function (i, val) {
            var tmp = val.Validate(wf.activityHelper.DraftingActivity, wf.activityHelper.EndActivity);
            if (!tmp.result) {
                result.result = false;
                result.errorMessage += tmp.errorMessage;
            }
        });

        if (result.result) {
            if (template.versionId == undefined) {
                template.versionId = template.id;
                template.versionNum = 0;
            }
            template.packageId = $("#packageName option:selected").val();
            template.orgId = wf.orgId;
            template.templateName = $("#templateName").val();
            template.description = $("#description").val();
            template.imgurl = $("#txtImg").val();
            $.request('/workflow/template/publish', template, function () {
                alert("成功");
                templateStatus = TemplateStatus.Open;
                SqlHelper.GetAllTemplate({packageName: '', id: ''});
                $('#save').modal('hide');
            });

        }
        else {
            alert(result.errorMessage);
        }
    },
    ChangeID: function () {
        template.guid = Guid.NewGuid();
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.ChangeID();
        });
        $.each(wf.rules, function (i, val) {
            val.ChangeID();
        });
    },
    Open: function () {
        var me = this;
        var layerNum = $.layer({
            type: 1,
            title: false,
            move: [$("#divOpenTitle"), true],
            fix: false,
            closeBtn: true,
            shadeClose: false,
            shade: [0.5, '#000', true],
            border: [5, 0.3, '#666', true],
            offset: ['50%', '50%'],
            area: ['750px', '400px'],
            page: {dom: $("#divOpen")},
            success: function () {
            }
        });
        $(".xubox_main").css("background-color", "transparent");
        OrgHelper.BindOrgForOpen(SqlHelper.OrgList);


        $("#btnOpenOK").unbind();
        $("#btnOpenCancel").unbind();
        $("#btnOpenOK").click(function () {
            if (openTemplateId == undefined || openTemplateId == null || openTemplateId.length == 0) {
                alert("请选择一个模板！");
                return;
            }

            wf.mask.css("display", "block");
            layer.close(layerNum);
            setTimeout(me.Wait, 100);

        })
        $("#btnOpenCancel").click(function () {
            layer.close(layerNum);
        })
    },
    wait: function () {
        var me = this;
        template = SqlHelper.GetTemplateById(openTemplateId);
//编辑
        if (template.activities) {
            wf.orgId = template.orgId;
            SqlHelper.GetAllJob();
            this.load(template);
            this.CanOperation = true;
            this.islock = true;
            // toolbar.Edit(undefined);
            wf.templateStatus = TemplateStatus.Open;
            wf.openTemplateId = null;
            wf.mask.css("display", "none");
        } else {
            //新增
            wf.orgId = app.baseorgId;
            SqlHelper.GetAllJob();
            wf.canvasHelper.CreateTemplate();
            me.CanOperation = true;
            me.UnBind();

            //myCanvas.unbind();
            //myCanvas.dblclick(function (e) {
            //    e.stopPropagation();
            //    wf.mouseOperation.leftbuttondoubleclick(e);

            //});

            me.BindEvent();
            templateStatus = TemplateStatus.New;
            template = pageParm.template;
            template.insert = false;
            $("#divTemplateName").css('display', 'none');
        }
    },
    Edit: function (image) {
        if (image == undefined) image = me.lockImage;
        this.islock = !this.islock;
        if (this.islock) {
            image.attr("src", "/assets/js/workflow/images/toolbar/unlock.png");
            this.UnBind();
            wf.canvas.dblclick(function (e) {
                wf.mouseOperation.leftbuttondoubleclick(e);
            });
        }
        else {
            this.UnBind();
            this.BindEvent();
            image.attr("src", "/assets/js/workflow/images/toolbar/lock.png");
        }
    },
    UnBind: function () {
        wf.workspace.unbind();
        $(document).unbind("keydown");
        wf.canvas.unbind();
    },
    BindEvent: function () {
        var me = this;
        wf.canvas.mousedown(function (e) {
            if (e.button == 0) {
                if (e.ctrlKey) {
                    wf.mouseOperation.ctrlKeybuttondown(e);
                }
                else {
                    wf.mouseOperation.leftbuttondown(e);
                }
            }
            else if (e.button = 1) {
                wf.mouseOperation.rightbuttondown(e);
            }
        }).mouseup(function (e) {
                if (e.button == 0)
                    wf.mouseOperation.leftbuttonUp(e);
            }
        ).mousemove(function (e) {
            wf.mouseOperation.mouseMove(e);
        });
        var isctrlKey = false;
        $(document).keydown(
            function (e) {
                if (e.keyCode == 17) isctrlKey = true;
                if (isctrlKey && e.keyCode == 90)
                    me.UndoCommand();
                else if (isctrlKey && e.keyCode == 89)
                    me.RedoCommand();
                else {
                    switch (e.keyCode) {
                        case 46:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.Dispose();
                                });
                                wf.selectedObjects = new Array();
                            }
                            else if (wf.gcommand == command.selectactivity)
                                wf.currentActivity.Dispose();
                            else if (wf.gcommand == command.selectrule)
                                wf.currentRule.Dispose();
                            break;
                        case 38:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X, val.position.Y - 1), true);
                                });
                            }
                            else if (wf.gcommand == command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X, wf.currentActivity.position.Y - 1), true);
                            return false;

                        case 40:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X, val.position.Y + 1), true);
                                });
                            }
                            else if (wf.gcommand == command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X, wf.currentActivity.position.Y + 1), true);
                            return false;
                        case 37:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X - 1, val.position.Y), true);
                                });
                            }
                            else if (wf.gcommand == command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X - 1, wf.currentActivity.position.Y), true);
                            return false;
                        case 39:
                            if (wf.selectedObjects.length > 0) {
                                $.each(wf.selectedObjects, function (i, val) {
                                    val.MoveActivity(new Point(val.position.X + 1, val.position.Y), true);
                                });
                            }
                            else if (wf.gcommand == command.selectactivity)
                                wf.currentActivity.MoveActivity(new Point(wf.currentActivity.position.X + 1, wf.currentActivity.position.Y), true);
                            return false;

                    }
                }
            }
        );
        wf.workspace.keyup(function () {
            ctrlKey = false;
        })


        wf.canvas.dblclick(function (e) {
            wf.mouseOperation.leftbuttondoubleclick(e);
        });


    },
    load: function (tmp, isImport) {
        debugger;
        template = tmp;
        if (template.templateName) {

        }
        if (wf.activityHelper == undefined)
            wf.activityHelper = new ActivityHelper();
        else {
            wf.activityHelper.Dispose();
            wf.activityHelper = new ActivityHelper();
        }


        $.each(template.activities, function (i, val) {
            if (val.isDel == 0) {
                var activity_coordinate = val.coordinate.split('$');
                var position = new Point(activity_coordinate[0], activity_coordinate[1]);
                var activity = wf.activityHelper.AddActivity(position, val.activityType, true);
                activity.id = val.id;
                if (val.activityType == ActivityType.start)
                    wf.activityHelper.StartActivity = activity;
                else if (val.activityType == ActivityType.end)
                    wf.activityHelper.EndActivity = activity;
                else if (val.activityType == ActivityType.drafting)
                    wf.activityHelper.DraftingActivity = activity;

                activity.isSelect = 0;
                val.guid = activity.guid;
                val.insert = 0;
                activity.SetProperty(val);
                activity.ResetActivity();
            }
        });

        $.each(template.rules, function (i, val) {
            if (val.isDel == 0) {
                val.insert = 0;
                var activity = wf.activityHelper.Activitys.first(val.fromGuid || val.fromActivityId, 'id');
                if (val.ruleType == 0) {
                    if (activity != null) {
                        var rule = new Rule(activity);
                        var position = val.coordinate.split(',');
                        var positionX = position[0].split('$');
                        var positionY = position[1].split('$');
                        if (positionX.length > 2)
                            for (j = 1; j < positionX.length - 1; j++) {
                                rule.AddPoint(new Point(positionX[j], positionY[j]));
                            }
                        var endac = wf.activityHelper.Activitys.first(val.toActivityId || val.fromActivityId, 'id');
                        wf.canvasHelper.AddRule(rule, endac, true);

                        rule.SetProperty(val);
                    }


                }
                else if (!isImport) {
                    if (activity.ActivityProperty.WF_RULE == undefined)
                        activity.ActivityProperty.WF_RULE = new Array();
                    activity.ActivityProperty.WF_RULE[activity.ActivityProperty.WF_RULE.length] = val;

                }
            }
        });

        $.each(wf.activityHelper.Activitys, function (i, val) {
            if (val.activityType == ActivityType.Merging) {
                var branchActivityId = wf.activityHelper.Activitys.first(val.ActivityProperty.branchActivityId);
                val.BranchingControl = branchActivityId;
                branchActivityId.MergingControl = val;
            }
        })


    }
}
